package com.wangjie.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jieshao
 * @date 2022/6/4 0:06
 *
 * 102. 二叉树的层序遍历
 */
public class Test03 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // while 循环控制从上向下一层层遍历
        while (!queue.isEmpty()) {
            // 记录这一层节点的值
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            // for 循环控制每一层从左向右遍历
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}